<template>
    <!--配合specTree.vue使用-->
    <view class="spec-tree-item">
        <view>
            <view v-if="noLast">
                <!-- 不是最后一组规格 -->
                <view class="sku-item">
                    <view class="sku-item-title"><text>{{ getTreeData[0].AttributeName }}：</text></view>
                    <view class="sku-item-select">
                        <view v-for="(item, index) in getTreeData" v-if="!item.IsLock" :key="index"
                            class="btn btn-gray-fill" :class="activeIndex === index ? 'btn-success-fill' : ''"
                            @click="_clickEvent(item, index)">
                            {{ item.ValueStr }}
                        </view>
                    </view>
                    <view v-if="getTreeData[0].ProductAttrList && getTreeData[0].ProductAttrList.length > 0"
                        class="spec-sub-tree">
                        <!--SpecTreeItem组件中调用SpecTreeItem组件-->
                        <!-- 根据上级规格的数量创建多个item，根据上级规格选中的项来显示对应的下级规格栏-->
                        <view v-for="(item, index) in getTreeData" v-show="activeIndex === index" :key="index">
                            <SpecTreeItem :data="data" :tree-data="item.ProductAttrList" :active-id="activeId"
                                :min-num="minNum" :limit-buy="limitBuy" @treeClickEvent="treeClickEvent"
                                @setCarListFunc="setCarListFunc" :tempType="tempType" :addNum="addNum" />
                        </view>
                    </view>
                </view>
            </view>
            <view v-else>
                <!-- 是最后一组规格 -->
                <!-- 根据上级规格的数量创建多个item，根据上级规格选中的项来显示对应的下级规格栏-->
                <view v-for="(item, index) in getTreeData" :key="index" class="num-item"
                    v-if="item.SkuModel && !item.IsLock">
                    <view v-if="item.ValueStr && getTreeData[0] && getTreeData[0].AttributeName" class="num-value">
                        <view class="price-sku">
                            {{ item.ValueStr }} <text class="num-price" style="padding-left: 4px;" v-if="IsShowStock">{{
                                showStockMessage(item.SkuModel.Stock) }}</text>
                        </view>
                        <view class="flex-v-c">
                            <point v-if="data.IsPointReward > 0" :minPoints="item.SkuModel.ProductUnitPrice.Points" />
                            <view class="num-price num-price-bold" v-else>￥{{ getShowPrice(item,
                                item.SkuModel.ProductUnitPrice.Price) }}</view>
                            <view class="num-price" style="padding-left: 12rpx"
                                v-if="item.SkuModel.ProductUnitPrice.RetailPrice">零售价:￥{{ getShowPrice(item,
                                    item.SkuModel.ProductUnitPrice.RetailPrice) }}</view>
                        </view>
                        <view class="num-price" v-if="item.SkuModel.Remark">{{ item.SkuModel.Remark }}</view>
                    </view>
                    <view v-else class="mask-box">默认规格<view class="num-price" v-if="item.SkuModel.Remark">{{
                        item.SkuModel.Remark }}</view>
                    </view>
                    <view v-if="item.SkuModel.Stock <= 0 && data.IsLackRegister == 1">
                        <view class="">
                            <view class="append-msg" @click="register(index)"> 缺货登记 </view>
                        </view>
                    </view>
                    <view v-else-if="tempType == 0">
                        <view class="input-number-box">
                            <text class="btn-minus" :class="item.Amount <= 0 ? 'color-shadow' : ''" @click="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    -1,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                                ">-</text>
                            <view class="btn-input-box">
                                <input v-model="item.Amount" type="digit" :cursor-spacing="isIos
                                    ? 110 + (getTreeData.length - 1 - index) * 65
                                    : 100 + (getTreeData.length - 1 - index) * 50
                                    " :adjust-position="true" maxlength="10" max="9999999999" class="btn-input"
                                    @click="inputclick(item)" @blur="
                                        changeAmount(
                                            item,
                                            item.Amount,
                                            item.Stock,
                                            0,
                                            minNum,
                                            item.Ratio,
                                            limitBuy,
                                            item.AddNum,
                                            1,
                                        )
                                        " />
                                <!--:focus="isFocus" :selection-start="selectionStart" :selection-end="selectionEnd" @focus="focusinput(item,index)" -->
                            </view>
                            <text class="btn-plus" :class="item.Amount * item.Ratio >= item.Stock ||
                                (item.Amount * item.Ratio >= limitBuy && limitBuy > 0)
                                ? 'color-shadow'
                                : ''
                                " @click="
                                    changeAmount(
                                        item,
                                        item.Amount,
                                        item.Stock,
                                        1,
                                        minNum,
                                        item.Ratio,
                                        limitBuy,
                                        item.AddNum,
                                    )
                                    ">+</text>
                        </view>
                        <!-- <text class="num-price">库存：{{ item.SkuModel.Stock }}</text> -->
                        <text class="num-price num-price-orange" style="padding-top: 4px;">金额: {{ getShowPrice(item,
                            item.SkuModel.ProductUnitPrice.Price * item.Amount) }}</text>
                        <!-- <text class="num-price" v-if='!IsShowStock'>{{ item.SkuModel.Stock && item.SkuModel.Stock >0?"有货":"无货" }}</text> -->
                    </view>
                    <view v-else>
                        <view class="input-number-box">
                            <text class="btn-minus" :class="item.Amount <= 0 ? 'color-shadow' : ''" @click="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    -1,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                                ">-</text>
                            <view class="btn-input-box">
                                <input v-model="item.Amount" type="digit" :cursor-spacing="isIos
                                    ? 110 + (getTreeData.length - 1 - index) * 65
                                    : 100 + (getTreeData.length - 1 - index) * 50
                                    " :adjust-position="true" maxlength="10" max="9999999999" class="btn-input" @blur="
                                        changeAmount(
                                            item,
                                            item.Amount,
                                            item.Stock,
                                            0,
                                            minNum,
                                            item.Ratio,
                                            limitBuy,
                                            item.AddNum,
                                        )
                                        " />
                            </view>
                            <text class="btn-plus" @click="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    1,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                                ">+</text>
                        </view>
                    </view>
                    <num-popup v-if="numPopShow" :amount="item.Amount" @close="numPopupClose"
                        @up="numPopupUp"></num-popup>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapMutations, mapGetters } from "vuex"
import SpecTreeItem from "@/components/productCategory/spec-tree-item.vue"
import point from "./point.vue"

import utilsOld from "@/utils/utilsOld.js"
import { getAmountInTempCart, getAmountInTempCartAct } from "@/utils/tempCartUtil.js"
import numPopup from "@/components/order/num-popup.vue"
import storage from "@/uni-sub-base/utils/storage.js"
import { eventBus } from "@/utils/eventBus.js"
import { getPlatform } from "@/uni-sub-base/utils/platformUtil.js"
export default {
    name: "SpecTreeItem",
    components: {
        SpecTreeItem,
        numPopup,
        point,
    },
    props: {
        data: {
            // 数据
            type: Object,
            required: true,
        },
        treeData: {
            type: Array,
            default() {
                return []
            },
        },
        activeId: {
            type: Number,
            default: -1,
        },
        minNum: {
            type: Number,
            default: 0,
        },
        limitBuy: {
            type: Number,
            default: 0,
        },
        isSingle: {
            type: Boolean,
            default: false,
        },
        tempType: {
            type: Number,
            default: 0,
        },
        addNum: {
            type: Number,
            default: 1,
        },
    },
    watch: {
        //监听临时购物车数据
        getTempCartData(data) { },
    },
    computed: {
        ...mapGetters(["getTempCartData"]),
    },
    data() {
        return {
            numPopShow: false,
            activeIndex: 0,
            numValue: 0,
            noLast: false,
            getTreeData: [],
            objItem: 0,
            cartDatas: [],
            isIos: false,
            currindex: -1,
            isFocus: false,
            selectionStart: -1,
            selectionEnd: 0,
            IsShowStock: "",
        }
    },
    mounted() {
        if (getPlatform() == "ios") {
            this.isIos = true
        } else {
            this.isIos = false
        }
        this.getTreeData = this.treeData
        console.log("this.getTreeData:", this.getTreeData)
        this.noLast =
            this.getTreeData &&
            this.getTreeData.length > 0 &&
            this.getTreeData[0].ProductAttrList &&
            this.getTreeData[0].ProductAttrList.length > 0
        if (!this.noLast) {
            this.getTreeData.forEach((e) => {
                this.getCurrentNum(e)
            })
        }
        this.$forceUpdate()
        //监听广播 获取购物车数据
        eventBus.$on("SET_CART_FOR_SUB", (msg) => {
            if (msg) {
                this.cartDatas = msg
                if (!this.noLast) {
                    this.getTreeData.forEach((e) => {
                        this.getCurrentNum(e)
                    })
                }
                this.$forceUpdate()
            }
        })
        //广播获取获购物车数据
        eventBus.$emit("GET_CART_DATA_FOR_SUB", "")
        this.showStockMessage()
    },
    destroyed() {
        //取消监听
        eventBus.$off("SET_CART_FOR_SUB")
    },
    methods: {
        showStockMessage(num) {
            console.log("num:", num)
            let info = storage.getCache("webInfo")
            if (!this.IsShowStock) {
                this.IsShowStock = info.IsShowStock
                return
            }
            if (info.IsShowStock) {
                this.IsShowStock = true
                if (info.ShowStockMessageList.length) {
                    let list = info.ShowStockMessageList
                    for (let i = 0; i < info.ShowStockMessageList.length; i++) {
                        if (list[i].MaxValue == 0 && num >= list[i].MinValue) {
                            return list[i].Message
                        }
                        if (num >= list[i].MinValue && num <= list[i].MaxValue) {
                            return list[i].Message
                        }
                    }
                    return "库存：" + num
                } else {
                    return "库存：" + num
                }
            } else {
                this.IsShowStock = false
            }
        },
        register(index) {
            let data = this.data
            let info = this.getTreeData[index]
            storage.setCache("")
            this.easyGoTo(
                "/pages_shop/packet/product/register?info=" +
                encodeURIComponent(JSON.stringify(info)) +
                "&data=" +
                encodeURIComponent(JSON.stringify(data)),
            )
            // uni.navigateTo({
            // 	url:'/pages_shop/packet/product/register?info='
            // 	+JSON.stringify(info)+'&data='+JSON.stringify(data),
            // })
        },
        getShowPrice(item, price) {
            if (item.PriceDigits) {
                return parseFloat(Number(price).toFixed(item.PriceDigits))
            } else {
                let productDisplay = storage.getCache("productDisplay")
                if (productDisplay) {
                    return parseFloat(
                        Number(price).toFixed(
                            productDisplay.PriceDecimalPlaces ? productDisplay.PriceDecimalPlaces : 2,
                        ),
                    )
                }
            }
            return parseFloat(price)
        },
        inputclick(item) {
            this.objItem = item.Amount
        },
        getCurrentNum(item) {
            if (this.tempType == 0) {
                this.cartDatas.forEach((e) => {
                    e.newSubItems.forEach((v) => {
                        if (v.ProductId == item.ProductId) {
                            v.SubItems.forEach((sub) => {
                                if (sub.SkuId == item.SkuId && item.UnitId == sub.UnitId) {
                                    item.Amount = sub.Amount
                                }
                            })
                        }
                    })
                })
            } else if (this.tempType == 1) {
                let amount = getAmountInTempCart(item)
                item.Amount = amount
            } else if (this.tempType == 3) {
                let amount = getAmountInTempCartAct(item)
                item.Amount = amount
            }
            if (item.Amount > 0) {
                this.setCarListFunc(item)
            }
        },
        //获取购买数量
        getAmount(num) {
            return num
        },
        // 节点点击事件
        _clickEvent(item, index) {
            this.activeIndex = index
            console.log("this.activeIndex:", this.activeIndex)

            // 如果有传递事件函数，则调用事件函数并传递当前节点数据及组件
            this.treeClickEvent(item, index)
        },
        changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum, blur) {
            console.log(item)
            if (item.SkuModel.LimitBuy > 0) {
                LimitBuy = item.SkuModel.LimitBuy
            }
            if (num == 999999999 && type == 1) {
                return false
            }
            if (item.SkuModel.AddNum > 0) {
                addNum = item.SkuModel.AddNum
            } else {
                addNum = this.addNum
            }
            if (item.SkuModel.MinimumOrder > 0) {
                minNum = item.SkuModel.MinimumOrder
            }
            if (blur) {
                if (UnitRatio == 1 && addNum > 0) {
                    if (!(num % addNum === 0)) {
                        this.easyToast("请输入" + addNum + "的倍数")
                        num = addNum
                        item.Amount = addNum
                    }
                }
            }
            const _oldAmount = item.Amount
            num = Number(num)
            addNum = UnitRatio && UnitRatio == 1 ? addNum : 1
            addNum = addNum == 0 ? 1 : addNum
            if (this.tempType == 1 || this.getAppSet().NoCheckStock) {
                if (type != 0) {
                    item.Amount = parseFloat(Number(num + Number(type) * addNum).toFixed(item.NumDigits))
                    if (type == -1 && item.Amount * UnitRatio < minNum) {
                        item.Amount = 0
                    } else if (item.Amount * UnitRatio < minNum) {
                        minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                        // let addN = minNum % addNum
                        let newNum = minNum
                        item.Amount = newNum
                    }
                } else {
                    if (num > 0) {
                        // let addN = num % addNum
                        let newNum = num
                        item.Amount = newNum
                        if (item.Amount * UnitRatio < minNum) {
                            minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                            // let addN = minNum % addNum
                            let newNum = minNum
                            item.Amount = newNum
                        }
                    } else {
                        item.Amount = 0
                    }
                }

                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            if (_oldAmount !== item.Amount || type === 0) {
                const _obj = {}
                _obj.ProductId = item.ProductId
                _obj.Amount = item.Amount
                _obj.SkuId = item.SkuId
                _obj.UnitId = item.UnitId
                _obj.UnitName = item.UnitName
                _obj.ValueId = item.ValueId
                _obj.Ratio = item.Ratio
                _obj.CartProductName = this.data.ProductName
                _obj.CartProductPrice = item.V_FactPrice
                _obj.CartProductImage = item.SkuModel.SkuImg
                _obj.CartProductAttribute = item.V_AttributeNameValue

                // 同步多规格要加入购物车的数据
                this.setCarListFunc(_obj)
                this.$forceUpdate()
            }
        },
        setCarListFunc(obj) {
            this.$emit("setCarListFunc", obj)
            this.$forceUpdate()
        },
        treeClickEvent(item, index) {
            this.$emit("treeClickEvent", item, index)
        },
        numPopupClose(e) {
            this.numPopShow = false
        },
        numPopupUp(e) {
            // this.batchItem.Amount = e

            this.numPopShow = false
        },
    },
}
</script>
<style lang="scss" scoped>
.append-msg {
    border: 2rpx solid #ff9403;
    color: #ff9403;
    border-radius: 50rpx;
    padding: 4rpx 20rpx;
    font-size: 24rpx;
}

.spec-tree-item {
    .sku-item {
        display: flex;
        flex-direction: column;
        margin-bottom: 20rpx;

        .sku-item-title {
            text {
                color: #666666;
            }
        }

        .sku-item-select {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            margin: 20rpx 0 0;

            .btn {
                min-width: 100rpx;
                border-radius: $border-radius-10;
                margin-right: 20rpx;
                margin-bottom: 20rpx;
            }
        }
    }

    .num-title {
        display: flex;
        flex-direction: row;
        margin-bottom: 20rpx;
        border-top: solid 1rpx $app-color-input-bg;
        padding-top: $app-page-padding;

        .title-label {
            display: flex;
            flex: 1;
        }

        .buy-num {
            display: flex;
            width: 234rpx;
            justify-content: center;
        }
    }
}

.num-item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 24rpx;
    align-items: center;

    text {
        display: flex;
        flex: 1;
    }

    .num-value {
        font-size: 28rpx;
        color: $color-gray-1;
    }

    .price-sku {
        display: flex;
        align-items: center;
    }

    .num-price {
        font-size: 20rpx;
        color: $color-gray-3;
    }

    .num-price-bold {
        color: $color-orange-1;
        font-weight: bold;
        font-size: 26rpx;
    }

    .num-price-orange {
        color: $color-orange-1;
    }
}

.num-item-class {}

.btn-input-box {
    width: 103rpx !important;
    margin: 0 10rpx !important;

    .btn-input {
        font-size: 26rpx;
        display: block;
        width: 103rpx !important;
    }
}

.mask-box {
    flex: 1;
    color: #333;
    font-size: $font-size-28;
}

.product-parameter {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 24rpx;
    color: #333333;
    font-weight: bold;
    height: 80rpx;
    background: #fff9ec;
    margin: 0 -24rpx;
    padding: 0 24rpx;
    margin-bottom: 24rpx;
}
</style>
